﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Practices.Unity;
using Web.SystemConfig.Services;

using EPlanet.Web.UI.WebControls;
using System.Data;
using Common;
using DreamBuilder.Core.Message;
using CommonModule;
using DreamBuilder.UI.UserControls;
using DreamBuilder.Core.Container;
using DreamBuilder.Core.Log;
using Web.SystemLogin.Business;
using System.Threading;






namespace Web.Views.SystemConfig
{
    public partial class Auth_UserEdit : PageBase
    {
        #region 控件及变量定义
        /// <summary>
        /// Business类
        /// </summary>
        [Dependency]
        public IAuth_User Auth_UserComponent
        {
            get;
            set;
        }

        [Dependency]
        public ICodeTable CodeTableService
        {
            get;
            set;
        }
        #endregion

        #region PageLoad方法

        protected void Page_Load(object sender, System.EventArgs e)
        {try{
            SetPageProperty();
            InitControlsCultureInfo();
            if (!IsPostBack)
            {
                ShowEdit();
            }
            CreateToolMenu(Toolbar1, ToolMenuType.TYPE_Edit);
            base.CheckEditAuthorities(base.CurrentPageState);
        }
        catch (Exception ex)
        {
            WriteErrorLog(ex.Message);
            ExceptionMsg();
        }
        }

        /// <summary>
        /// 设置页面的菜单属性
        /// </summary>
        private void SetPageProperty()
        {
            this.DBHelpName = DBHelperString.Dictionary;
            base.MenuID = "ePlanet.Configuration.Auth_User";
            if (!IsPostBack)
            {
                if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                {
                    base.CurrentPageState = PageState.State_New;
                }
                else
                {
                    base.CurrentPageState = PageState.State_Edit;
                    base.PKValue = Request.QueryString.Get("pkValue");
                }
            }
            if (Request["Parent_ID"] != null)
            {
                ViewState["MainOrgID"] = Request["Parent_ID"].ToString();
            }
        }

        /// <summary>
        /// 显示列表,为列表控件的单据id赋值
        /// </summary>
        private void ShowEdit()
        {
            ucedit.VoucherID = "vch_Auth_User";
            ucedit.PKValue = base.PKValue;
        }

        /// <summary>
        /// 初始化控件多语信息
        /// </summary>
        private void InitControlsCultureInfo()
        {
            this.TabControl1.Items[0].Caption = GetString("Auth_User");
            this.TabControl1.Items[1].Caption = GetString("OrgRole");
            this.litUserRole.Text = GetString("UserRole");
            this.litOrgRole.Text = GetString("OrgRole");
            this.btnViewRole.InnerText = GetPublicString("Button", "btnViewRole");
        }

        #endregion

        #region OnPreRender方法

        /// <summary>
        /// 重写OnPreRender方法
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            string UserID = GetUserID();

            //初始化角色ListCheckBox
            LoadRoles(UserID);
            LoadOrgRoles(UserID);
            //初始化查看角色按钮
            ShowViewRoleBtn(UserID);
            base.OnPreRender(e);
            //设置用户ID
            SetUserIDEnabled();
            //by 刘英男
            SetControlEnabled();
            //加上默认的用户id
            LoadRolesType();

        }
        //by 刘英男
        private void SetControlEnabled()
        {

            //初始所属单位
            if (base.CurrentPageState == PageState.State_New)
            {
                string MainParentid = Request.QueryString.Get("Parent_ID").ToString();
                string OrgContorlID = this.ucedit.GetEditControlID("P_Auth_User", "ORG_ID");
                string OrdercontrolID = this.ucedit.GetEditControlID("P_Auth_User", "Order_Num");
                //2014年5月10日  是否登录，改为默认为可以登录
                string CanLoginID = this.ucedit.GetEditControlID("P_Auth_User", "Can_login");
                if (!string.IsNullOrEmpty(CanLoginID))
                {
                    Control canlogin_cl = this.ucedit.FindControl(CanLoginID);
                    if (canlogin_cl is RBLBool)
                    {
                        RBLBool rbl_Canlogin = (RBLBool)canlogin_cl;
                        //第一个选项为可登录
                        rbl_Canlogin.Value = true;
                    }
                }
                if (!string.IsNullOrEmpty(OrgContorlID))
                {
                    Control cnl = this.ucedit.FindControl(OrgContorlID);
                    if (cnl is RefEditor)
                    {
                        RefEditor OrgContorl = cnl as RefEditor;

                        //  OrgContorl.RefNameValue = Auth_UserComponent.GetOrgNameByNumber(MainParentid);
                        OrgContorl.RefNameValue = ViewState["MainOrgID"].ToString().Equals("FristQuery") ? "请选择相应组织单元" : Auth_UserComponent.GetOrgNameByNumber(ViewState["MainOrgID"].ToString());

                        OrgContorl.RefCodeValue = ViewState["MainOrgID"].ToString();
                    }
                }
                else
                {
                    RedirectList(Request.QueryString.Get("pkValue").ToString());
                    //如果获取失败 跳转回主页面
                }
                if (!string.IsNullOrEmpty(OrdercontrolID))
                {
                    Control ordercnl = this.ucedit.FindControl(OrdercontrolID);
                    if (ordercnl is TextBox)
                    {
                        TextBox orderText = ordercnl as TextBox;
                        orderText.Text = (Auth_UserComponent.MaxOrgNum(MainParentid)+1).ToString();
                    }
                    else
                    {
                        RedirectList(Request.QueryString.Get("pkValue").ToString());
                        //如果获取失败 跳转回主页面
                    }
                }
            }
        }

        /// <summary>
        /// 设置用户ID
        /// </summary>
        private void SetUserIDEnabled()
        {
            TextBox txtUser_ID = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_User", "User_ID")) as TextBox;
            if (!string.IsNullOrEmpty(Request.QueryString.Get("pkValue")))
            {
                //modify by lyn 20120222 和用户已确认去掉只读权限
                //TextBox txtLogin_ID = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_User", "Login_ID")) as TextBox;
                //设置编辑时用户id字段和登录字段只读
                if (txtUser_ID != null)
                {
                    txtUser_ID.Enabled = false;
                    //txtLogin_ID.Enabled = false;
                }
            }
            else
            {
                txtUser_ID.Text = Guid.NewGuid().ToString();
                txtUser_ID.Enabled = false;
            }
        }

        #region 初始化角色ListCheckBox

        private void LoadRolesType()
        {
            //角色类别
            DataSet RoleTypes = CodeTableService.GetCodeTableDataByType("RoleType");
            this.gv_Role.PageSize = 50;
            this.gv_Role.DataSource = RoleTypes;
            this.gv_Role.DataBind();
        }


        private void LoadRoles(string userID)
        {
            //this.chklstRoles.Items.Clear();
            //DataTable dt = Auth_UserComponent.SelectRolesByUserID(userID);
            //ListItem li;

            //if (dt != null)
            //{
            //    foreach (DataRow dr in dt.Rows)
            //    {

            //        li = new ListItem((string)dr["Role_Name"]);
            //        if (dr["HasRole"].ToString().ToBoolean())
            //        {
            //            li.Selected = true;
            //            //add 1 to the value to save the checked status
            //            li.Value = "1_" + dr["Role_ID"].ToString();
            //        }
            //        else
            //        {
            //            li.Selected = false;
            //            // add 0 to the value to save the checked status
            //            li.Value = "0_" + dr["Role_ID"].ToString();
            //        }
            //        chklstRoles.Items.Add(li);
            //    }
            //}
        }

        private void LoadOrgRoles(string userID)
        {
            this.chklstOrgRoles.Items.Clear();
            DataTable dt = Auth_UserComponent.SelectOrgRolesByUserID(userID);
            ListItem li;
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    li = new ListItem((string)dr["Role_Name"]);
                    if (dr["HasRole"].ToString().ToBoolean())
                    {
                        li.Selected = true;
                        //add 1 to the value to save the checked status
                        li.Value =  dr["Role_ID"].ToString();
                    }
                    else
                    {
                        li.Selected = false;
                        // add 0 to the value to save the checked status
                        li.Value = dr["Role_ID"].ToString();
                    }
                    chklstOrgRoles.Items.Add(li);
                }
            }
        }

        #endregion

        #region 获取userID

        private string GetUserID()
        {
            TextBox user = this.ucedit.FindControl(this.ucedit.GetEditControlID("P_Auth_User", "User_ID")) as TextBox;
            string UserID = user.Text;
            return UserID;
        }
        #endregion

        #region ShowViewRoleBtn函数

        private void ShowViewRoleBtn(string UserID)
        {
            if (CurrentPageState==PageState.State_New)
            {
                this.btnViewRole.Visible = false;
            }
            else
            {
                btnViewRole.Attributes.Add("href", "../Account/Profile.aspx?UserID=" + UserID);
            }
        }

        #endregion

        #endregion

        #region 事件处理方法
        /// <summary>
        /// 工具条事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Toolbar1_MenuItemClick(object sender, MenuItemClickEventArgs e)
        {try{
            switch (e.EventItem.ID.ToString().ToLower())
            {
                case "tbsave":
                    this.Validate();
                    if (this.IsValid)
                    {
                        OnSaveData();
                    }
                    break;
                case "tbcancel":
                    RedirectList(Request.QueryString.Get("pkValue").ToString());
                    break;
                case "tbhelp":
                    break;
            }
        }
        catch (Exception ex)
        {
            WriteErrorLog(ex.Message);
            ExceptionMsg();
        }
        }

        protected void gv_Role_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataRowView drv = (DataRowView)e.Row.DataItem;
                string UserID = GetUserID();
                DataTable dt = Auth_UserComponent.SelectRolesByUserID(UserID);
                DataRow[] rows = dt.Select("Role_Type='" + drv["CodeTableID"] + "'");
                Control c = e.Row.Cells[1].Controls[0];
                if (c is CheckBoxList)
                {
                    ListItem li;
                    CheckBoxList cbl = (CheckBoxList)c;
                    foreach (DataRow dr in rows)
                    {

                        li = new ListItem((string)dr["Role_Name"]);
                        if (dr["HasRole"].ToString().ToBoolean())
                        {
                            li.Selected = true;
                            //add 1 to the value to save the checked status
                            li.Value = "1_" + dr["Role_ID"].ToString();
                        }
                        else
                        {
                            li.Selected = false;
                            // add 0 to the value to save the checked status
                            li.Value = "0_" + dr["Role_ID"].ToString();
                        }
                        cbl.Items.Add(li);
                    }
                }
            }
        }
        #endregion

        #region 保存
        /// <summary>
        /// 保存数据
        /// </summary>
        private void OnSaveData()
        {

            System.Data.DataSet dsInfo = new System.Data.DataSet();
            dsInfo.Tables.Add(ucedit.GetEditDataTable());
            if (dsInfo != null)
            {
                if (dsInfo.Tables[0].Rows[0]["P_Auth_User.ORG_ID"] == DBNull.Value || dsInfo.Tables[0].Rows[0]["P_Auth_User.ORG_ID"].ToString().Length == 0)
                {
                    DataTable dtCheckOrg = Auth_UserComponent.CheckOrg(dsInfo.Tables[0]);
                    if (dtCheckOrg.Rows.Count > 1)
                    {
                        string orgName = string.Empty;
                        foreach (DataRow dr in dtCheckOrg.Rows)
                        {
                            orgName += dr["ORG_Name"].ToString() + " ";
                        }
                        DisplayMessage("This user have in these organizations:" + orgName + ",You can only set this user in these organizations.");
                        return;
                    }
                }
                if (String.IsNullOrEmpty(Request.QueryString["pkValue"].ToString()))
                {
                    dsInfo.Tables[0].Rows[0]["P_Auth_User.User_ID"] = Guid.NewGuid().ToString();
                    string userLoginID = dsInfo.Tables[0].Rows[0]["P_Auth_User.Login_ID"].ToString();
                    string userCheckID = dsInfo.Tables[0].Rows[0]["P_Auth_User.User_ID"].ToString();
                    string userOALoginID = dsInfo.Tables[0].Rows[0]["P_Auth_User.OALogin_ID"].ToString();
                    bool userChecklogin = Auth_UserComponent.CheckLoginID(userLoginID);
                    bool userCheckPrimary = Auth_UserComponent.CheckUserPrimary(userCheckID);
                    bool userCheckOA = Auth_UserComponent.OACheckLoginID(userLoginID);
                    if (userChecklogin)
                    {
                        this.ShowMsg("此CNPC登录名已存在，请更改用户登录名。");
                        DisplayMessage("此CNPC登录名已存在，请更改用户登录名。");
                        return;
                    }
                    if (userCheckPrimary)
                    {
                        this.ShowMsg("此用户标识已存在，请更改用户标识。");
                        DisplayMessage("此用户标识已存在，请更改用户标识。");
                        return;
                    }
                    if (userCheckOA)
                    {
                        this.ShowMsg("此OA登录名已存在，请更改用户登录名。");
                        DisplayMessage("此OA登录名已存在，请更改用户登录名。");
                        return;
                    }
                }
                //处理主表数据
                HandleMainTable(dsInfo.Tables[0]);
                string mainKey = dsInfo.Tables[0].Rows[0][0].ToString(); 
                string pkName=dsInfo.Tables[0].Rows[0]["P_Auth_User.User_Name"].ToString();

                ResultInfo result = Auth_UserComponent.SaveData(dsInfo, this.gv_Role, dsInfo.Tables[0].Rows[0]["P_Auth_User.User_ID"].ToString());
                if (result.bSuccess == true)
                {
                    if ((Request["pkValue"] == null || Request["pkValue"].Trim().Length == 0))
                    {
                        Auth_UserComponent.ModifyUser("P_Auth_User", "Create_User", this.CurrentUser.User_ID, "Create_Time", DateTime.Now, "User_ID", mainKey);
                        Auth_UserComponent.ModifyUser("P_Auth_User", "Modify_User", this.CurrentUser.User_ID, "Modify_Time", DateTime.Now, "User_ID", mainKey);
                        string operationMessage = this.CurrentUser.Real_Name + "新增了" + pkName + "[" + mainKey + "]用户";
                        WriteUserLog(operationMessage,OracleLogType.System);
                    }
                    else
                    {
                        Auth_UserComponent.ModifyUser("P_Auth_User", "Modify_User", this.CurrentUser.User_ID, "Modify_Time", DateTime.Now, "User_ID", mainKey);
                        string operationMessage = this.CurrentUser.Real_Name + "修改了" + pkName + "[" + mainKey + "]用户";
                        WriteUserLog(operationMessage,OracleLogType.System);
                    }
                    RedirectList(Request.QueryString.Get("pkValue").ToString());
                }
                else
                {
                    DisplayMessage(result.ErrorDesc);
                }
            }

        }

        private void HandleMainTable(DataTable dataTable)
        {
            if (string.IsNullOrEmpty(Request.QueryString.Get("pkValue")))
            {
                dataTable.Rows[0]["P_Auth_User.User_Pwd"] = EncryptDecrypt.EncryptPassword("000000", "MD5");
            }

        }


        #endregion

        #region 页面跳转
        /// <summary>
        /// 跳转到列表页面
        /// </summary>
        private void RedirectList(string User_ID)
        {
            string parentID = Request.QueryString.Get("Parent_ID").ToString();
            Response.Redirect("Auth_User.aspx?Parent_ID=" + parentID);                
           // Response.Redirect("Auth_User.aspx");
        }
        #endregion

        #region OnInit
        override protected void OnInit(EventArgs e)
        {
            //
            //CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
            //
            InitializeComponent();
            base.OnInit(e);
        }
        /// <summary>
        /// 添加页面及控件事件
        /// </summary>
        private void InitializeComponent()
        {
            this.Toolbar1.MenuItemClick += new EPlanet.Web.UI.WebControls.MenuItemClickedEventHandler(Toolbar1_MenuItemClick);
        }
        #endregion
    }
}
